package Algorithm.handleString;

/**
 * 125. 验证回文串 https://leetcode.cn/problems/valid-palindrome/
 */
public class IsPalindrome {

    public static void main(String[] args) {
        new IsPalindrome().isPalindrome2(".,");
    }

    /**
     * 思路一：直接使用api操作
     */
    public boolean isPalindrome(String s) {
        s = s.toLowerCase().replaceAll("[^a-z0-9]+", "");
        return new StringBuilder(s).reverse().toString().equals(s);
    }

    /**
     * 思路二：双指针扫描
     * 注意在循环中也不能让lowIndex指针越过highIndex
     */
    public boolean isPalindrome2(String s) {
        int lowIndex=0, highIndex=s.length()-1;
        char low, high;
        while (lowIndex < highIndex) {
            low = s.charAt(lowIndex);
            high = s.charAt(highIndex);
            while (!Character.isLetterOrDigit(low) && lowIndex < highIndex) {
                low = s.charAt(++lowIndex);
            }
            while (!Character.isLetterOrDigit(high) && highIndex > lowIndex) {
                high = s.charAt(--highIndex);
            }
            if (Character.toLowerCase(low) != Character.toLowerCase(high)) {
                return false;
            }
            lowIndex++;
            highIndex--;
        }
        return true;
    }
}
